package com.centaline.androidsalesblog.activities.mine;

import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.view.View;
import android.widget.LinearLayout;

import com.centaline.androidsalesblog.R;
import com.centaline.androidsalesblog.activities.news.ChatActivity;
import com.centaline.androidsalesblog.adapter.ContactAdapter;
import com.centaline.androidsalesblog.adapter.viewholder.ContactVH;
import com.centaline.androidsalesblog.base.BaseActivity;
import com.centaline.androidsalesblog.constants.ExtraConstant;
import com.centaline.androidsalesblog.iml.RecyclerViewItemOnClickListener;
import com.centaline.androidsalesblog.model.databaseobject.BizUnitDo;
import com.centaline.androidsalesblog.model.databaseobject.StaffDo;
import com.centaline.androidsalesblog.rx.database.RxDataBase;
import com.centaline.androidsalesblog.utils.ContactUtil;
import com.centaline.androidsalesblog.utils.RongUserIdUtil;
import com.centanet.framework.glide.GlideLoad;
import com.trello.rxlifecycle.ActivityEvent;

import java.util.ArrayList;
import java.util.Locale;

import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * 最近联系人
 * <p/>
 * Created by fusl1 on 2015/12/22.
 */
public class ContactActivity extends BaseActivity {

    private LinearLayout ll_default;
    private RecyclerView rv_contact;

    private ArrayList<StaffDo> list = new ArrayList<>();
    private ContactAdapter contactAdapter;

    @Override
    protected int setLayoutId() {
        return R.layout.activity_contact;
    }

    @Override
    protected void findViews() {
        ll_default = (LinearLayout) findViewById(R.id.ll_default);
        rv_contact = (RecyclerView) findViewById(R.id.rv_contact);
    }

    @Override
    protected void initViews() {
        setUniversalToolbar(R.string.title_contact);
        contactAdapter = new ContactAdapter(this, GlideLoad.initRound(this), list, new RecyclerViewItemOnClickListener<StaffDo>() {
            @Override
            public void onItemOnClick(final StaffDo staffDo, int tag) {
                if (staffDo == null)
                    return;
                switch (tag) {
                    case 1:
                        startActivity(new Intent(ContactActivity.this, ChatActivity.class)
                                .putExtra(ExtraConstant.TargetId, RongUserIdUtil.getSatffId(staffDo.getStaffNo())));
                        break;
                    case 2:
                        ContactUtil.sendMsg(ContactActivity.this, staffDo.getMobile());
                        break;
                    case 3:
                        new AlertDialog.Builder(ContactActivity.this)
                                .setMessage(String.format(Locale.CHINA, "拨打:%s,%s",
                                        staffDo.getBigCode(), staffDo.getExtCode()))
                                .setPositiveButton("拨打", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        ContactUtil.dial(ContactActivity.this, staffDo.getBigCode(), staffDo.getExtCode());
                                    }
                                }).setNegativeButton("取消", null)
                                .create()
                                .show();
                        break;
                    default:
                        break;
                }
            }
        });
        rv_contact.setLayoutManager(new LinearLayoutManager(this));
        rv_contact.setHasFixedSize(true);
        rv_contact.setAdapter(contactAdapter);
        ItemTouchHelper.Callback callback = new ItemTouchHelper.Callback() {
            @Override
            public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
                return makeMovementFlags(ItemTouchHelper.ACTION_STATE_IDLE, ItemTouchHelper.START);
            }

            @Override
            public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
                return false;
            }

            @Override
            public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
                delete(viewHolder.getAdapterPosition());
            }

            @Override
            public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
                super.clearView(recyclerView, viewHolder);
                ContactVH contactVH = (ContactVH) viewHolder;
                contactVH.itemView.setBackgroundResource(R.drawable.ic_table_normal);
            }

            @Override
            public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) {
                if (actionState != ItemTouchHelper.ACTION_STATE_IDLE) {
                    ContactVH contactVH = (ContactVH) viewHolder;
                    contactVH.itemView.setBackgroundResource(R.drawable.ic_table_selected);
                }
                super.onSelectedChanged(viewHolder, actionState);
            }
        };

        ItemTouchHelper itemTouchHelper = new ItemTouchHelper(callback);
        itemTouchHelper.attachToRecyclerView(rv_contact);
        bizUnit();
        getHistory();
    }

    private void bizUnit() {
        RxDataBase.getBizUnit()
                .compose(this.<BizUnitDo>bindUntilEvent(ActivityEvent.DESTROY))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<BizUnitDo>() {
                    @Override
                    public void call(BizUnitDo bizUnitDo) {
                        contactAdapter.setImEnable(bizUnitDo.isShowTalk());
                    }
                });
    }

    /**
     * 获取
     */
    private void getHistory() {
        RxDataBase.getHistoryStaffs()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(this.<ArrayList<StaffDo>>bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new Action1<ArrayList<StaffDo>>() {
                    @Override
                    public void call(ArrayList<StaffDo> staffDos) {
                        list.addAll(staffDos);
                        contactAdapter.notifyDataSetChanged();
                        if (list.size() > 0) {
                            refreshUi();
                        }
                    }
                });
    }

    /**
     * 删除
     */
    private void delete(final int position) {
        RxDataBase.deleteStaff(list.get(position))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(this.<Boolean>bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new Action1<Boolean>() {
                    @Override
                    public void call(Boolean aBoolean) {
                        list.remove(position);
                        contactAdapter.notifyItemRemoved(position);
                        if (list.size() == 0) {
                            refreshUi();
                        }
                    }
                });
    }

    private void refreshUi() {
        final boolean isEmpty = list.size() == 0;
        ll_default.setVisibility(isEmpty ? View.VISIBLE : View.GONE);
        rv_contact.setVisibility(isEmpty ? View.GONE : View.VISIBLE);
    }
}
